package com.lsk.mps.backend.controller;

import com.lsk.mps.backend.aspect.annotation.JsonReturn;
import com.lsk.mps.backend.service.UserService;
import com.lsk.mps.backend.util.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@RestController
@RequestMapping("/api/admin/")
public class AdminController {
    @Autowired
    private UserService userService;

    @JsonReturn
    @GetMapping("/user/pages")
    public Object userPages() {
        return userService.userTotalPages();
    }

    @JsonReturn
    @GetMapping("/user/list")
    public Object userList(Integer page) {
        return userService.allUsers(page);
    }

    @JsonReturn
    @GetMapping("/user/grant")
    public Object userGrant(Integer targetUID, String role) {
        userService.grantUser(targetUID, role);
        return "Success";
    }

    @JsonReturn
    @PostMapping("/user/import")
    public Object importExcel(MultipartFile file) {
        try {
            String originalFilename = file.getOriginalFilename();
            String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = "/tmp/mps-backend/" + UUID.randomUUID() + fileType;
            File tempFile = new File(fileName);
            file.transferTo(tempFile);
            userService.importUsersFromExcel(tempFile);
            tempFile.delete();
            return "Success";
        } catch (StatusCode statusCode) {
            throw statusCode;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @JsonReturn
    @PostMapping("/user/create")
    public Object userCreate(String username, String password, String role) {
        userService.createUser(username, password, role);
        return "Success";
    }

    @JsonReturn
    @DeleteMapping("/user/delete")
    public Object userDelete(Integer targetUID) {
        userService.deleteUser(targetUID);
        return "Success";
    }
}
